<?php
require_once("config.php");

/*
	Function: RILtext
	
	Parses the url with Read It Later API, so it returns only the text of the page. 
	If it doesn't find anything, it tries with the 'more' option.
	
	Parameters:
	
		url: URL to parse.
	
	Returns:
	
		The text parsed, or an empty string if there was any error.
	
	See also:
		
		http://readitlaterlist.com/api/docs/#text
*/
function RILtext($url)
{
	$ch = curl_init();
	curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); // No SSL verification, but we're not transmitting sensitive info.
	curl_setopt($ch, CURLOPT_URL, 'https://text.readitlaterlist.com/v2/text?apikey='.RIL_API_KEY.'&url='.$url);
	curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
	$content = curl_exec($ch);
	$info = curl_getinfo($ch);
	if(!($info['http_code'] == 200 || $info['http_code'] == '200'))
	{
		curl_close($ch);
		return "";
	}
	if(empty($content))
	{
		// It returns empty, so we try to get something with "More" mode.
		curl_setopt($ch, CURLOPT_URL, 'https://text.readitlaterlist.com/v2/text?mode=more&apikey='.RIL_API_KEY.'&url=$url');
		$content = curl_exec($ch);
		$info = curl_getinfo($ch);
		if(!($info['http_code'] == 200 || $info['http_code'] == '200'))
		{
			curl_close($ch);
			return "";
		}
	}
	curl_close($ch);
	return $content;	
}



/*
	Function: parseFavs
	
	Parses the favorites of an user (an array of tweets) and returns the array with all the neccessaryv variables to fill HTML.
	
	Parameters:
	
		favs: An array of tweets.
		limit: Maximum number of tweets to parse.
		
	Returns:
	
		An array with all the data needed to fill the page. The array will look like this:
		
		(start code)
		'text' => Tweet text
		'screen' => Screen name of the user.
		'user' => The name of the user.
		'avatar' => The URL to the user's image.
		'link' => A link to the tweet.
		'id' => The tweet's ID, provided by Twitter.
		'date' => Date of the tweet, formatted.
		'res' => Indicates whether we detected attachments on the tweet or not.
		(end)	
*/
function parseFavs($favs, $limit=20)
{
	$arr;
	$i = 0;
	// Run over all the tweets
	foreach ($favs as $tweet)
	{
		// Linkify the text
		$patterns[0]="/https?:\/\/[A-Za-z]*\.?[A-Za-z0-9]+\.[A-Za-z]*\/?[A-Za-z0-9_\-\.\/\?#%=]*/";
		$patterns[1]="/^@([A-Za-z0-9_]+)| @([A-Za-z0-9_]+)/";
		$patterns[2]="/^(#[A-Za-z0-9_]+)| (#[A-Za-z0-9_]+)/";
		 
		$replace[0]='<a href="$0">$0</a>';
		$replace[1]=' <a href="http://twitter.com/$1$2">@$1$2</a>';
		$replace[2]=' <a href="http://twitter.com/search?q=$1$2">$1$2</a>';
				
		$arr[$i]['text'] = preg_replace($patterns, $replace, $tweet->text);
		// Get all links.
		unset($urls);
		$num=preg_match_all("/https?:\/\/[A-Za-z]*\.?[A-Za-z0-9]+\.[A-Za-z]*\/?[A-Za-z0-9_\-\.\/\?#%=]*/", $tweet->text, $urls);
		if ($num > 0) // URLs found
		{
			$arr[$i]['res']= true; 
		}
		
		$arr[$i]['screen'] = $tweet->user->screen_name;
		$arr[$i]['user']=$tweet->user->name;
		$arr[$i]['avatar']=$tweet->user->profile_image_url;
		$arr[$i]['link'] = "http://twitter.com/".$tweet->user->screen_name."/status/".$tweet->id;
		$arr[$i]['id'] = $tweet->id;
		$arr[$i]['date'] = date("M d, H:i", strtotime($tweet->created_at));
		
		if ($i>=$limit)
		{
			break;
		}
		$i=$i+1;
	}
	
	return $arr;
}

/*
	Function: getAuth
	
	Gets the token and token secret for the user. Also stores the token and token secret in the session and cookie.
	
	Parameters:
		auth: Passed by reference. Array in which the token and token secret will be stored, returning ['token'] and ['token_secret'].
	
	Returns:
		True if successful. False if not. The token and token_secret are stored in the array passed as argument.
*/
function getAuth(&$auth)
{
	$auth=array();
	/* Get user access tokens out of the session. */
	if( empty($_SESSION['token']) || empty($_SESSION['token_secret'])) 
	{
		// Check if we have the cookie and the user is registered on our DB.
		if (!(empty($_COOKIE['token'])))
		{
			$auth['token']=$_COOKIE['token'];
			$res = getTokenSecret($token);
			if (empty($res))
			{
				return false;
			}
			else
			{	
				$_SESSION['token'] = $token;
				$auth['token_secret'] = $res['token_secret'];
				$_SESSION['token_secret'] = $res['token_secret'];
				return true;
			}
		}
		else
		{
			return false;
		}
	}
	else
	{
		$auth['token'] = $_SESSION['token'];
		$auth['token_secret'] = $_SESSION['token_secret'];
		setcookie("token", $token, time()+30*24*60*60);
		return true;
	}
}

/* 
	Function: parseResources
	
	Parses the resources (images, videos, webs..) in a string.
	
	Parameters:
		text: String containing the resources.
		resources: Passed by reference. Array with all the resources, each one with url and HTML embed code.
		
	Returns:
		True if resources were found. False if not.
*/
function parseResources($text, &$resources)
{
	$resources = array();
	$num = preg_match_all("/https?:\/\/[A-Za-z]*\.?[A-Za-z0-9]+\.[A-Za-z]*\/?[A-Za-z0-9_\-\.\/\?#%=]*/", $text, $urls);
	$res = false;
	if ($num > 0) // URLs found
	{	 			
		$resources = array();
		// Parse the URLs.
		foreach($urls[0] as $url)
		{
			// In case there is a multimedia resource, we will avoid using RIL mobilizer and show only the resource.
			$matches;
			// Twitpic: Get image id, show thumbnail.
			if(preg_match("#http://twitpic.com/([A-Za-z0-9_\-]+)#", $url, $matches)>0)
			{	
				$resources[] = array ( 'url' => $url, 'code'=> '<img src="http://twitpic.com/show/large/'.$matches[1].'" />');
				$res = true;
			}
			
			// Same as above, YFrog.
			else if(preg_match("#http://yfrog.com/([A-Za-z0-9_\-]+)#", $url, $matches)>0)
			{
				$resources[] = array ( 'url' => $url, 'code'=> '<img src="http://yfrog.com/'.$matches[1].':medium" />');
				$res = true;
			}
			
			// Plixi (now lockerz) doesn't have a consistent way to show images. Avoiding until further notice (always wanted to say that)
			
			// YouTube. We get the video ID from the URL.
			else if( (preg_match("#http://youtu.be/([A-Za-z0-9_\-]+)#", $url, $matches)>0) || (preg_match("#http://www.youtube.com/watch?v=([A-Za-z0-9_\-]+)#", $url, $matches)>0))
			{
				$resources[] = array ( 'url' => $url, 'code'=> '<iframe src="http://www.youtube.com/embed/'.$matches[1].'"></iframe>');
				$res = true;
			}
			
			// Vimeo. I don't bother with this, as Vimeo has a low market share, and it doesn't have its own shortener. 
			//	Very few possibilites of finding a non-shortened Vimeo URL.
			
			// Normal webpage, calling RIL mobilizer.
			else
			{
				$text=RILtext($url);
				// Trim the text to see if it's empty, because sometimes RIL returns a lot of spaces.
				if(trim($text)!="") {
					$resources[] = array ( 'url' => $url, 'code' => $text );
					$res = true;
				}
			}
		}
	}
	return $res;
}
 ?>